# Copyright (c) 2025 Li Auto Inc. and its affiliates
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
#     http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.

#! /bin/bash

function gettop
{
    local TOPFILE=build/make/root.mk
    if [ -n "$TOPDIR" -a -f "$TOPDIR/$TOPFILE" ] ; then
        (cd $TOPDIR; PWD= /bin/pwd)
    else
        if [ -f $TOPFILE ] ; then
            PWD= /bin/pwd
        else
            local HERE=$PWD
            local T=
            while [ \( ! \( -f $TOPFILE \) \) -a \( $PWD != "/" \) ]; do
                \cd ..
                T=`PWD= /bin/pwd -P`
            done
            \cd $HERE
            if [ -f "$T/$TOPFILE" ]; then
                echo $T
            fi
        fi
    fi
}

function getoutdir
{
    local outdir=$(gettop)/out/${TARGET_PRODUCT}
    echo "$outdir"
}

function check
{
    if [ ! ${TARGET_PRODUCT} ]; then
        echo "Please lunch first!"
        kill -INT $$
    fi
    echo
}

# make modules
function mm()
{
    check

    cd $(gettop)
    make install $*
    make compile_commands.json
    cd -
}

# make modules all
function mma()
{
    check
    cd $(gettop)
    rm -rf $(getoutdir)
    make install $*
    make compile_commands.json
    cd -
}

function py-pkg-install()
{
    cd $(gettop)
    pip install -r build/scripts/requirements.txt --extra-index-url https://gitlabee.chehejia.com/api/v4/projects/10037/packages/pypi/simple
    cd -
}

function addcompletions()
{
    local T dir f

    # Keep us from trying to run in something that isn't bash.
    if [ -z "${BASH_VERSION}" ]; then
        return
    fi

    # Keep us from trying to run in bash that's too old.
    if [ ${BASH_VERSINFO[0]} -lt 3 ]; then
        return
    fi

    dir="sdk/bash_completion"
    if [ -d ${dir} ]; then
        for f in `/bin/ls ${dir}/[a-z]*.bash 2> /dev/null`; do
            echo "including $f"
            . $f
        done
    fi

    complete -C "bit --tab" bit
}

unset LUNCH_MENU_CHOICES
declare -A PRODUCT_DICT=()

function __add_product()
{
    local new_product=$1
    local c
    for p in ${PRODUCT_DICT[@]} ; do
        if [ "$new_product" = "$p" ] ; then
            return
        fi
    done

    PRODUCT_DICT[$new_product]="$2:$3"

    LUNCH_MENU_CHOICES=(${LUNCH_MENU_CHOICES[@]} $new_product)
}

function add_product()
{
    local product_file=$1
    local product_name product_dir toolchain

    product_name=$(basename ${product_file} .product)
    product_dir=$(dirname ${product_file})

    source ${product_file}

    if [ -n "$toolchain" ]; then
        __add_product $product_name $product_dir $toolchain
    fi
}

function add_all_products()
{
    local plat_dir
    local product_path=()
    cd $(gettop)

    plat_dir="build/make/ prebuilts/platforms/"

    mapfile -d '' product_path < <(find ${plat_dir} -type f -name "*.product" -print0 2>/dev/null)

    product_path=($(printf "%s\n" "${product_path[@]}" | sort))

    for file in "${product_path[@]}"; do
        add_product "$file"
    done
}

function print_lunch_menu()
{
    local uname=$(uname)
    echo
    echo "You're building on" $uname
    echo
    echo "Lunch menu... pick a combo:"

    local i=1
    local choice
    for choice in ${LUNCH_MENU_CHOICES[@]}
    do
        echo "     $i. $choice"
        i=$(($i+1))
    done

    echo
}

function lunch()
{
    # check if the options list is empty
    # [[ ${#LUNCH_MENU_CHOICES[@]} == 0 ]] && echo "Lunch choices empty." ; exit -1

    # step1: get user choice and store it into answer
    local answer

    if [ "$1" ] ; then
        answer=$1
    else
        print_lunch_menu
        echo -n "Which would you like? [${LUNCH_MENU_CHOICES[0]}] "
        read answer
    fi

    [[ -z "$answer" ]] && answer=1

    # step2: transform the "answer" into choice strings
    local selection=

    if (echo -n $answer | grep -q -e "^[0-9][0-9]*$")
    then
        if [ $answer -le ${#LUNCH_MENU_CHOICES[@]} ]
        then
            case `echo $SHELL` in
                *bash*)
                    selection=${LUNCH_MENU_CHOICES[$(($answer-1))]}
                    ;;
                *zsh*)
                    selection=${LUNCH_MENU_CHOICES[$answer]}
                    ;;
                *)
                    echo "WARNING: Only bash/zsh is supported, use of other shell would lead to erroneous results"
                    ;;
            esac
        fi
    else
        selection=$answer
    fi

    echo ${selection}
    local product="${PRODUCT_DICT[${selection}]}"

    export TARGET_PRODUCT=${selection%-*}
    export TARGET_BUILD_VARIANT=${selection##*-}
    export TARGET_PRODUCT_DIR=${product%%:*}
    export TARGET_TOOLCHAIN=${product#*:}
}

function croot()
{
    local T=$(gettop)
    if [ "$T" ]; then
        if [ "$1" ]; then
            \cd $(gettop)/$1
        else
            \cd $(gettop)
        fi
    else
        echo "Couldn't locate the top of the tree.  Try setting TOPDIR."
    fi
}

function cgrep()
{
    rg -g '*.c' -i "`echo "DECLARE_MVBS_TEST $*" | sed 's/ /.*/g'`" $(gettop)/app/test_cases/
}

function tgrep()
{
    rg -g 'TestProfile' -i "`echo " $*" | sed 's/ /.*/g'`" $(gettop)/app/test_cases/
}

function mgrep()
{
    grep -rn $* $(gettop)/app/test_cases/
}

function mvbs-cfg()
{
    python3 -B $(gettop)/tools/mvbs-cfg/mvbs-config.py $*
}

function mvbs-idl()
{
    python3 -B $(gettop)/tools/mvbs-idl/mvbs-idl.py $*
}

if [ "x$SHELL" != "x/bin/bash" ]; then
    case `echo $SHELL` in
        *bash*)
            ;;
        *zsh*)
            ;;
        *)
            echo "WARNING: Only bash/zsh is supported, use of other shell would lead to erroneous results"
            ;;
    esac
fi

function pc-test-env()
{
    cd $(gettop)/out/test/

    export MVBS_LOCATOR_INFO=127.0.0.1/24
    export PATH=./bin:$PATH
    export LD_LIBRARY_PATH=./soc/lib:$LD_LIBRARY_PATH
}

function j6m-test-env()
{
    cd $(gettop)/out/test/

    export MVBS_ECU_IP=172.31.3.71
    export MVBS_LOCATOR_INFO=172.31.3.111/24

    export PATH=./bin:./tools/j6m/adpro4.0:$PATH
    export LD_LIBRARY_PATH=./vbs/lib:$LD_LIBRARY_PATH

    export MVBS_OTA_CMD=$(gettop)/app/tools/cicd/tools/j6m/adpro4.0/j6m_rcore_ota.sh
}

function ota()
{
    if [ ! -v MVBS_OTA_CMD ]; then
        echo "You haven't setup your test environment."
    fi

    ${MVBS_OTA_CMD} $*
}

add_all_products
addcompletions

# vim: set expandtab ts=4 sw=4 sts=4 tw=80:
